package servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import database.Connect;
import database.Queries;

/**
 * Servlet implementation class userServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       String adminCode="123";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			
			String action = request.getParameter("action");
			if (action==null){
				response.sendError(500);
			}
			if (action.equals("register")){
				registerUser(request, response);
				return;  
			}
			if (action.equals("delete")){
				deleteUser(request, response);
				return;
			}
			if (action.equals("registerusercourse")){
				registerToCourse(request, response);
				return;
			}
			
			if (action.equals("unregisterusercourse")){
				unregisterFromCourse(request, response);
				return;
			}
			
			if (action.equals("edit")){
				editDetails(request,response);
				return;
			}
	}



	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void deleteUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		Connection con=null;
		PreparedStatement stmt=null,stmt2=null;
		try {
			con=Connect.getConnection();
			con.setAutoCommit(false);
			stmt=con.prepareStatement("" +
					"DELETE FROM users WHERE username=?");
			stmt.setString(1,request.getParameter("name"));
			stmt.executeUpdate();
			//delete user from "registers" table
			stmt2=con.prepareStatement("" +
			"DELETE FROM registers WHERE username=?");
			stmt2.setString(1,request.getParameter("name"));
			stmt2.executeUpdate();
			//if all is fine, success
			ServletOutputStream out = response.getOutputStream();
			out.print("success");
			con.commit();
			response.setStatus(200);
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500);
		    try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return;
			}
		}
		finally{
			try {
				if(con!=null) {
					con.setAutoCommit(true);
					stmt.close();
					stmt2.close();
					con.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
				response.sendError(600);
			}	
		}
		return;
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void registerToCourse(HttpServletRequest request,
			HttpServletResponse response)
			throws IOException {
		
		Connection con=null;
		PreparedStatement stmt = null;
		String username=request.getParameter("username");
		String course=request.getParameter("course");
		try {
			con=Connect.getConnection();
			con.setAutoCommit(false);
			stmt=con.prepareStatement("" +
					"INSERT INTO registers values (?,?);");
			stmt.setString(1,course);
			stmt.setString(2,username);
			stmt.executeUpdate();
			response.setStatus(200);
			con.commit();
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500);
			try {
				stmt.close();
				con.rollback();
				return;
			} catch (SQLException e1) {
				e1.printStackTrace();
				return;
			}
		}
		finally{
			if(con!=null) {
				try {
					con.setAutoCommit(true);
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void unregisterFromCourse(HttpServletRequest request,
			HttpServletResponse response)
			throws IOException {
		
		Connection con=null;
		PreparedStatement stmt = null;
		String username=request.getParameter("username");
		String coursename=request.getParameter("coursename");
		try {
			con=Connect.getConnection();
			con.setAutoCommit(false);
			stmt=con.prepareStatement("" +
					"DELETE FROM registers WHERE username=? AND coursename=?;");
			stmt.setString(1,username);
			stmt.setString(2,coursename);
			stmt.executeUpdate();
			response.setStatus(200);
			con.commit();
			return;
		} catch (SQLException e) {
			e.printStackTrace();
			response.sendError(500);
			try {
				stmt.close();
				con.rollback();
				return;
			} catch (SQLException e1) {
				e1.printStackTrace();
				return;
			}
		}
		finally{
			if(con!=null) {
				try {
					con.setAutoCommit(true);
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void editDetails(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pwdChange=request.getParameter("pwd");
		String fullnameChange = request.getParameter("fullname");
		String phoneChange = request.getParameter("phone");
		String username = request.getUserPrincipal().getName();
		if (pwdChange!=null){ //password change
			 try {
				String update = "UPDATE users SET password=? WHERE username='"+username+"';";
				updateField(update,pwdChange);
			} catch (Exception e) {
				e.printStackTrace();
				response.sendError(500);
			}
		}
		if (fullnameChange!=null){ //fullname change
			try {
				String update = "UPDATE users SET name=? WHERE username='"+username+"';";
				updateField(update,fullnameChange);
			} catch (Exception e) {
				e.printStackTrace();
				response.sendError(500);
			}
		}
		if (phoneChange!=null){ //phone change
			try {
				String update = "UPDATE users SET phone=? WHERE username='"+username+"';";
				updateField(update,phoneChange);
			} catch (Exception e) {
				e.printStackTrace();
				response.sendError(500);
			}
		}
		return;
	}
	
	/**
	 * 
	 * @param updateQuery
	 * @param content
	 * @throws Exception
	 */
	private void updateField(String updateQuery,String content) throws Exception {
		Connection con = null;
		PreparedStatement stmt=null;
		try {
			con=Connect.getConnection();
			con.setAutoCommit(false);
			stmt = con.prepareStatement(updateQuery);
			stmt.setString(1,content);
			stmt.executeUpdate();
		    stmt.close();
		    con.commit();
		    return;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
		    	con.rollback();
				stmt.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
				throw e1;
			}	
			throw e;
		}
		finally 
		{
		    if (con!=null) try {con.setAutoCommit(true);con.close();}catch (Exception ignore) {throw ignore;}
		}
		
	}

	/**
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void registerUser(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		String role=request.getParameter("roles");
		if(role.equals("admin"))
		{
			String code=request.getParameter("code");
			if(!adminCode.equals(code))
			{
				response.sendError(400, "wrong code");
				return;
			}
		}
		String name=request.getParameter("name");
		String phone=request.getParameter("phone");
		Connection con = null;
		PreparedStatement stmt=null;
		try {
			con=Connect.getConnection();
			con.setAutoCommit(false);
			if (Queries.isStudentExists(con, username)){
				response.sendError(405, "username exists");
				return;
			}
			stmt = con.prepareStatement(
					"INSERT INTO users values(?,?,?,?,?);");
			stmt.setString(1,username);
			stmt.setString(2,password);
			stmt.setString(3,role);
			stmt.setString(4,name);
			stmt.setString(5,phone);
			stmt.execute();
			HttpSession s = request.getSession();
			s.setAttribute("username",username);
			s.setAttribute("role",role);
			response.sendRedirect("index.jsp");
		    stmt.close();
		    con.commit();
		    return;
		} catch (SQLException e) {
			response.sendError(500);
			e.printStackTrace();
		    try {	
				stmt.close();
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return;
			}
			return;
		}
		finally 
		{
		    if (con!=null) try {con.setAutoCommit(true);con.close();}catch (Exception ignore) {}
		}
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}
